// Utility functions
$.fn.getRow = function() {
  return $(this).parent('tr').prevAll().length;
};
$.fn.getCol = function() {
  return $(this).prevAll().length;
};
$.fn.cell = function(r, c) {
  return $('tr:nth-child('+(r+1)+') td:nth-child('+(c+1)+')', this);
};

function randomColor() {
  var a = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);
  var c = Math.floor(Math.random() * 256);
  return "rgb("+a+","+b+","+c+")";
}

// Plays sound from the snd/ folder. Removes element when playback is done.
var soundCounter = 0;
function playSound(path) {
  path = "snd/" + path;
  audio = $("<audio />").attr({"src": path, "id": "a"+soundCounter}).css("display", "none");
  $("body").append(audio);
  audio[0].play();
  audio.on("ended", {"id":"a"+soundCounter}, function(e) {
    $(e.data.id).remove();
  });
  soundCounter++;
};
//Takes two arrays with length length as arguments, returns first index
//if none were found, returns length
function firstFalse(used, length) {
  for (var i = 0; i < length; i++)
    if (!used[i])
      return i;
  return length;  
}

function find(val, arr, length) {
  for (var i = 0; i < length; i++)
    if (arr[i] == val)
      return i;
  return -1;
}

//0 means disabled; 1 means enabled;
var popupStatus = 0;
var currentPopup = null;

//loading popup with jQuery magic!
$.fn.loadPopup = function(){
  //loads popup only if it is disabled
  disablePopup();
  //Images don't want to load propertly. Let us give them time to load.
  setTimeout(function(self) {

    self.centerPopup();
    $("#popupBackground").fadeIn("slow");
    self.fadeIn("slow");
    popupStatus = 1;
    currentPopup = self;
  }, 100, this);

};

function popupActive() {
	return popupStatus == 1;
}

function disablePopup(){
  //disables popup only if it is enabled
  if(popupActive()){
    $("#popupBackground").fadeOut("slow");
    currentPopup.fadeOut("slow");
    popupStatus = 0;
  }
}

$.fn.centerPopup = function(){
  //request data for centering
  var windowWidth = document.documentElement.clientWidth;
  var windowHeight = document.documentElement.clientHeight;
  var popupHeight = this.height();
  var popupWidth = this.width();  
  //centering
  this.css({
    "position": "absolute",
    "top": windowHeight/2-popupHeight/2,
    "left": windowWidth/2-popupWidth/2
  });
  $("#popupBackground").css({
    "height": windowHeight
  });  
  //Add x to close if it wasn't there.
  $("#popupCloserX").remove();
  this.append('<a href="#" id="popupCloserX" onclick="disablePopup()">X</a>');
};

$.fn.statusPopup = function() {
  var status;
  if (game)
    status = game.status();
  else
    status = BattleShips.statusCode.playbackEnded;
  var redirect = null;
  redirect = function(x) {
    $("#redirectText").text("Suuname sind pealehele "+x+" sekundi pärast.");
    if (x > 0)
      setTimeout(redirect, 1000, x - 1);
    else {
      var loc = window.location.pathname;
      loc = loc.substr(0, loc.lastIndexOf("/")+ 1);
      window.location.replace(loc);
    }
  };
  
  if (status === BattleShips.statusCode.notEnoughShips) {
    this.html("<h2>Paiguta paremale väljale 10 laeva!</h2>");
  }
  else if (status === BattleShips.statusCode.enoughShips) {
    this.html("<h2>Soovid mängu alustada?</h2>");
    this.append('<a href="#" class="GameButton" id="acceptButtonStart" onClick="start()">Jah</a>');
    this.append('<a href="#" class="GameButton" id="declineButtonStart" onClick="disablePopup()">Ei</a>');
  }
  else if (status === BattleShips.statusCode.started) {
    this.html("<h2>Soovid mängu lõpetada?</h2>");
    this.append('<a href="#" class="GameButton" id="acceptButtonEnd" onClick="location.reload()">Jah</a>');
    this.append('<a href="#" class="GameButton" id="declineButtonEnd" onClick="disablePopup()">Ei</a>');    
  }
  else if (status === BattleShips.statusCode.won) {
    this.html("<h2>Võitsid mängu!</h2>");
    this.append('<img src="img/trophy.jpg" alt="trofee" />');
    this.append("<p id='redirectText'/>");
    redirect(5);
    //Cannot close this popup
    $("#popupBackground").off();
  }
  else if (status === BattleShips.statusCode.lost) {
    this.html("<h2>Kaotasid mängu. Haahaa.</h2>");  
    this.append("<p id='redirectText'/>");
    redirect(5);
    $("#popupBackground").off();
  }
  else if (status === BattleShips.statusCode.playbackEnded) {
    this.html("<h2>Playback ended.</h2>");  
    this.append("<p id='redirectText'/>");
    redirect(5);
    $("#popupBackground").off();
  }
  this.loadPopup();
};

function start() {
  disablePopup();
    $("#alustaButton").html("Lõpeta");
  game.startGame();
} 